const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const morgan = require('morgan')
const config = require('config');

const dateFormat = require('dateformat');
const template = require('art-template')
template.defaults.imports.dateFormat = dateFormat;

const app = express();

require('./model/connect')

app.use(bodyParser.urlencoded({extend: false}));
app.use(session({
  secret: 'secret key',
  saveUninitialized: false,
  cookie: {
    maxAge: 24 * 60 * 60 * 1000
  }
}))

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'art');
app.engine('art', require('express-art-template'));

app.use(express.static(path.join(__dirname, 'public')));

if (process.env.NODE_ENV === 'development') {
  // 在开发环境中 将客户端发送到服务端的请求信息打印到控制台中
  app.use(morgan('dev'))
} else {

}

console.log(config.get('title'));

const home = require('./route/home');
const admin = require('./route/admin');

app.use('/admin', (req, res, next) => {
  if (req.url != '/login' && !req.session.username) {
    res.redirect('/admin/login')
  } else {
    next()
  }
})

app.use('/home', home);
app.use('/admin', admin);

app.use((err, req, res, next) => {
  const result = JSON.parse(err)
  let params = []
  for (let attr in result) {
    if (attr != 'path') {
      params.push(attr + '=' + result[attr])
    }
  }
  res.redirect(`${result.path}?${params.join('&')}`)
})

app.listen(3000)
console.log('网站服务器启动成功localhost3000');